﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TaobaoERP.Core.Service;
using TaobaoERP.BusinessTaobao.TaobaoAPI;
using TaobaoERP.Entity;
using TaobaoERP.Core.Repository;
using Microsoft.Practices.EnterpriseLibrary.PolicyInjection;

namespace TaobaoERP.BusinessServices
{
    public class SettingsService 
    {
        /// <summary>
        /// 更新卖家商品目录
        /// </summary>
        public void UpdateItemcats(string SessionID, int? ParentID)
        {
            using (RepositoryContext db = new RepositoryContext())
            {
                //ItemCatsAPI APIProcessor = PolicyInjection.Create<ItemCatsAPI>();
                ItemCatsAPI APIProcessor = new ItemCatsAPI();
                List<ItemCat> listItemcats = APIProcessor.itemcats_get(ParentID.HasValue ? ParentID.Value : 0);

                //List<ItemCat> listItemcats = new ItemCatsAPI().itemcats_get(ParentID.HasValue?ParentID.Value:0);
                foreach (var item in listItemcats)
                {
                    int msg = (from f in db.GetTable<ItemCat>() where f.ID == item.ID select f.ID).Count();
                    if (msg == 0)
                    {
                        db.GetTable<ItemCat>().InsertAllOnSubmit<ItemCat>(listItemcats);
                    }
                }
                
                db.SubmitChanges();
            }
        }

        
        public List<ItemCat> ListItemcasts(int PageSize, int PageIndex,int ParentID)
        {
            RepositoryContext db = new RepositoryContext();

            var query = from f in db.GetTable<ItemCat>()
                        where f.ParentID == ParentID
                        select new
                        {
                            ID = f.ID,
                            IsParent = f.IsParent,
                            Name = f.Name,
                            ParentID = f.ParentID
                        };
            query = query.Skip(PageSize * PageIndex).Take(PageSize);
            //using (db.Connection)
            //{
                return db.ExecuteQuery<ItemCat>(query);
            //return ItemCatList.ToList<ItemCat>();

            //}
        }
        public int CountItemcasts(int ParentID)
        {
            //RepositoryContext db = new RepositoryContext();
            using (RepositoryContext db = new RepositoryContext())
            {
                //var ItemCatList = (from f in db.GetTable<ItemCat>() select f);
                var query = from f in db.GetTable<ItemCat>()
                            where f.ParentID == ParentID select f.ID;
                return query.Count();
                //return ItemCatList.ToList<ItemCat>();
            }
        }
    }
}
